﻿using System;
using System.IO;
using System.Linq;
using System.Web.DynamicData;
using System.Web.Security;
using System.Web.UI;
using NotAClue.Web.DynamicData;
using NotAClue.ComponentModel.DataAnnotations;

namespace DD_Extensions
{
    public partial class FileUploadField : FieldTemplateUserControl
    {

        public override Control DataControl
        {
            get { return Label1; }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // add CSS from meta data
            this.ApplyCss();
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            // get attributes
            var fileUploadAttribute = MetadataAttributes.GetAttributeOrDefault<FileUploadAttribute>();
            if (fileUploadAttribute == null)
                throw new InvalidOperationException("FileUpload must have valid FileUploadAttribute applied");

            //check if field has a value
            if (FieldValue == null)
            {
                Image1.Visible = false;
                Label1.Text = String.IsNullOrEmpty(fileUploadAttribute.FileNotPresentMessage) ? "File not present." : fileUploadAttribute.FileNotPresentMessage;
                Label1.Visible = true;
                return;
            }

            Label1.Text = FieldValueString;

            String displayImageUrl = fileUploadAttribute.DisplayImageUrl;
            String displayImageType = fileUploadAttribute.DisplayImageType;

            // get the file extension and make sure it is lower case
            String extension = (FieldValueString.Substring(
                FieldValueString.LastIndexOf(".") + 1,
                FieldValueString.Length - (FieldValueString.LastIndexOf(".") + 1))).ToLower();

            // check the file exists else throw validation error
            String filePath;

            // get primary key value
            var primaryKeyValue = Table.GetPrimaryKeyString(Row);

            if (fileUploadAttribute != null)
                filePath = UploadExtensionMethods.GetUploadPath(fileUploadAttribute.FileUploadPath, Table.Name, primaryKeyValue, Column.Name) + FieldValueString;
            else
                throw new InvalidOperationException("An FileUploadPath is required for the FileUpload FieldTemplate to work");

            // check file exists on file system
            if (!File.Exists(Server.MapPath(filePath)))
                return;

            // if either hyperlinks are disabled or the 
            // file does not exist then hide the link
            if (fileUploadAttribute.DisableHyperlink || !File.Exists(Server.MapPath(filePath)))
            {
                Label1.Text = FieldValueString;
                HyperLink1.Visible = false;
            }
            else
            {
                Label1.Visible = false;
                // Target="_blank" 
                HyperLink1.Target = fileUploadAttribute.OpenInNewWindow ? "_blank" : String.Empty;
                HyperLink1.Text = FieldValueString;
                HyperLink1.NavigateUrl = filePath;
            }

            // show the icon
            if (!String.IsNullOrEmpty(extension))
            {
                // set the file type image
                if (!String.IsNullOrEmpty(displayImageUrl))
                {
                    Image1.ImageUrl = String.Format(displayImageUrl, extension + "." + displayImageType);
                }
                else
                {
                    // if attribute not set the use default
                    Image1.ImageUrl = String.Format("~/images/{0}", extension + "." + displayImageType);
                }

                Image1.AlternateText = extension + " file";

                // apply attributes
                var imageFormat = MetadataAttributes.GetAttribute<ImageFormatAttribute>();
                if (imageFormat != null)
                {
                    // if either of the dims is 0 don't set it
                    // this will mean that the aspect will remain locked
                    if (imageFormat.DisplayWidth != 0)
                        Image1.Width = imageFormat.DisplayWidth;
                    if (imageFormat.DisplayHeight != 0)
                        Image1.Height = imageFormat.DisplayHeight;
                }
            }
            else
            {
                // if file has no extension then hide image
                Image1.Visible = false;
            }
        }
    }
}